/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.vdialog.view.template;

import offset.nodes.client.view.MappedSchemaNodeRenderer;
import offset.nodes.client.view.TreeNodeChooserDialog;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import offset.nodes.Constants;
import offset.nodes.client.chooser.view.TypeChooserDialog;
import offset.nodes.client.vdialog.model.template.AbstractTemplateNode;
import offset.nodes.client.model.HierarchyTree;
import offset.nodes.client.model.NodeTypes;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.vdialog.model.template.TemplateReferenceNode;
import offset.nodes.client.model.Server;
import offset.nodes.client.tree.model.TreeNodePanel;
import offset.nodes.client.tree.model.TreeNodePanelContainer;
import offset.nodes.client.model.TreeNodeUserObject;
import offset.nodes.client.virtual.model.jcr.QName;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeDefinition;

/**
 *
 * @author  Walter Lütgenau
 */
public class TemplateReferencePanel extends javax.swing.JPanel implements TreeNodePanel {

    class TextFieldDocumentListener implements DocumentListener {

        public void changedUpdate(DocumentEvent e) {
            validateOkButton();
        }

        public void insertUpdate(DocumentEvent e) {
            validateOkButton();
        }

        public void removeUpdate(DocumentEvent e) {
            validateOkButton();
        }
    }
    TreeNodePanelContainer container = null;
    SimpleNamespaceRegistry namespaces = SimpleNamespaceRegistry.getInstance();
    TypeChooserDialog newTypeChooser = null;
    Server server;
    TextFieldDocumentListener textFieldDocumentListener = new TextFieldDocumentListener();
    TreeNodeUserObject userObject;
    NodeTypes types = null;
    String pathNodeType;

    /** Creates new form FolderPanel
     * @param server the server model
     * @param types the node types repository
     */
    public TemplateReferencePanel(Server server, String pathNodeType) {
        this.server = server;
        this.pathNodeType = pathNodeType;
        initComponents();
    }

    public void setTypes(NodeTypes types) {
        this.types = types;
    }

    protected void validateExtendButton() {
        TreePath selected = container.getTree().getSelectionModel().getSelectionPath();
        if (selected == null) {
            return;
        }

        selected = selected.getParentPath();
        while (selected != null) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) selected.getLastPathComponent();
            AbstractTemplateNode userObject = (AbstractTemplateNode) node.getUserObject();
            if (userObject.getNodeType() != null) {
                extendButton.setEnabled(true);
                return;
            }

            selected = selected.getParentPath();
        }

        extendButton.setEnabled(false);
    }

    private void validateOkButton() {
        boolean ok = true;
        if (typeTextField.getText() == null || typeTextField.getText().length() == 0) {
            ok = false;
        }
        
        if ( (pathTextField.getText() == null || pathTextField.getText().length() == 0)) {
            ok = false;
        }

        container.enableOkButton(ok);
    }

    protected void setTemplateReference(TemplateReferenceNode definition) {
        if (definition.getQuery() != null) {
            typeTextField.setText(definition.getQuery());
        } else {
            typeTextField.setText("");
        }
        
        if ( pathTextField.getText() != null && pathTextField.getText().length() > 0)
            definition.setTemplatePath(pathTextField.getText());

        validateExtendButton();
        validateOkButton();
    }

    protected TemplateReferenceNode getTemplateReference() {
        TemplateReferenceNode template = new TemplateReferenceNode();

        template.setQuery(null);
        if ( typeTextField.getText().length() > 0)
            template.setQuery(typeTextField.getText());
        
        if ( typeTextField.getText() != null && typeTextField.getText().length() > 0) {
            String path = template.getSchemaPath();
            int indexSeparator = path.indexOf("/");
            if ( indexSeparator >= 0)
                path = path.substring(indexSeparator+1);
            NodeTypeDefinition definition = types.get(QName.valueOf(namespaces.toQNameString(path)));
            template.setNodeType(definition);
        }

        return template;
    }

    protected String[] toStringArray(TreePath path) {
        String[] names = new String[path.getPathCount()];
        int i = 0;
        while (path != null) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (node.getUserObject() != null && node.getUserObject() instanceof AbstractTemplateNode) {
                AbstractTemplateNode userObject = (AbstractTemplateNode) node.getUserObject();
                names[i++] = userObject.getSchemaPath();
            }

            path = path.getParentPath();
        }

        return names;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        folderNameButtonGroup = new javax.swing.ButtonGroup();
        typeLabel = new javax.swing.JLabel();
        typeTextField = new javax.swing.JTextField();
        typeTextField.getDocument().addDocumentListener(textFieldDocumentListener);
        extendButton = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        pathLabel = new javax.swing.JLabel();
        pathTextField = new javax.swing.JTextField();
        pathTextField.getDocument().addDocumentListener(textFieldDocumentListener);
        pathButton = new javax.swing.JButton();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("offset/nodes/client/vdialog/view/DialogBundle"); // NOI18N
        typeLabel.setText(bundle.getString("template.templatePanel.query")); // NOI18N

        extendButton.setText(bundle.getString("template.templatePanel.extendQuery")); // NOI18N
        extendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectExtendedType(evt);
            }
        });

        newButton.setText(bundle.getString("template.templatePanel.newQuery")); // NOI18N
        newButton.setPreferredSize(new java.awt.Dimension(67, 23));
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectNewType(evt);
            }
        });

        pathLabel.setText(bundle.getString("template.templateReferencePanel.path")); // NOI18N

        pathButton.setText("...");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(typeLabel)
                    .addComponent(pathLabel))
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(pathTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pathButton))
                    .addComponent(typeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 483, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(extendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(72, 72, 72))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(typeLabel)
                    .addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(extendButton))
                .addGap(64, 64, 64)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pathLabel)
                    .addComponent(pathButton)
                    .addComponent(pathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(123, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    private void selectExtendedType(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectExtendedType
        TreePath path = container.getTree().getSelectionModel().getSelectionPath();
        path = path.getParentPath();
        String[] mappedPathes = toStringArray(path);
        AbstractTemplateNode userObject = null;

        while (path != null) {
            DefaultMutableTreeNode current = (DefaultMutableTreeNode) path.getLastPathComponent();
            userObject = (AbstractTemplateNode) current.getUserObject();

            if (userObject == null) // reached root without finding base query. Something wrong here, return
                return;

            if (userObject.getQuery() != null && userObject.getQuery().indexOf("/") < 0) // found base query
                 break;
 
            path = path.getParentPath();
        }

        DefaultMutableTreeNode querySchemaNode = HierarchyTree.setupHierarchicalTree(userObject.getNodeType().getName(), userObject.getNodeType(), null, types, false, true);
        TreeNodeChooserDialog chooser = new TreeNodeChooserDialog(null, true, querySchemaNode);
        chooser.setCellRenderer(new MappedSchemaNodeRenderer(mappedPathes));
        chooser.setVisible(true);
        if (chooser.getReturnStatus() == TreeNodeChooserDialog.RET_OK) {
            DefaultMutableTreeNode selected = chooser.getSelectedNode();
            typeTextField.setText(getExtendedPath(querySchemaNode, selected, mappedPathes));
        }
 
}//GEN-LAST:event_selectExtendedType
    
    /**
     * Determine the query string from the selected schema node
     * 
     * @param schema the schema nodes displayed to the user
     * @param selected the schema node selected by the user
     * @param mappedPathes a string array of pathnames of the parent nodes of the current virtual folder/page/template
     * @return the query string
     */
    protected String getExtendedPath(DefaultMutableTreeNode schema, DefaultMutableTreeNode selected, String[] mappedPathes) {
        StringBuffer result = new StringBuffer();
        StringBuffer path = new StringBuffer();
        
        while( schema != null ) {
            if ( path.length() > 0)
                path.append("/");
            path.append(schema.toString());
            boolean isMapped = false;
            
            for( int i=0; i<mappedPathes.length; i++) {
                if ( path.toString().equals(mappedPathes[i])) {
                    isMapped = true;
                    break;
                }
            }
            
            if ( isMapped) {
                result = new StringBuffer(schema.toString());
                result.append("[ancestor()]");
            }
            else
                result.append("/"+schema.toString());
            
            if ( schema == selected )
                break;
            
            if ( schema.getChildCount() > 0) 
                schema = (DefaultMutableTreeNode) schema.getChildAt(0);
            else
                schema = null;
        }
        
        return result.toString();
    }
    
    private void selectNewType(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectNewType
        if (newTypeChooser == null) {
            newTypeChooser = new TypeChooserDialog(null, true, server, new QName(Constants.URI_NODES_DATA, ""));
        }
        newTypeChooser.setVisible(true);
        if (newTypeChooser.getReturnStatus() == TypeChooserDialog.RET_OK) {
            typeTextField.setText(namespaces.toPrefixName(newTypeChooser.getDefinition().getName()));

            validateOkButton();
        }
}//GEN-LAST:event_selectNewType

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton extendButton;
    private javax.swing.ButtonGroup folderNameButtonGroup;
    private javax.swing.JButton newButton;
    private javax.swing.JButton pathButton;
    private javax.swing.JLabel pathLabel;
    private javax.swing.JTextField pathTextField;
    private javax.swing.JLabel typeLabel;
    private javax.swing.JTextField typeTextField;
    // End of variables declaration//GEN-END:variables
    
    public void setPanel(TreeNodeUserObject userObject) {
        this.userObject = userObject;
        if ( userObject != null && userObject instanceof TemplateReferenceNode)
            setTemplateReference((TemplateReferenceNode) userObject);
    }

    public TreeNodeUserObject getUserObject() {
        return getTemplateReference();
    }

    public void setContainer(TreeNodePanelContainer container) {
        this.container = container;
    }
}
